package register

import (
	"context"
	"errors"
	"fmt"
	clientv3 "go.etcd.io/etcd/client/v3"
	"time"
)

func CreateETCDCli(option Option) (*clientv3.Client, error) {
	cli, err := clientv3.New(clientv3.Config{
		Endpoints:   option.Endpoints, // 节点
		DialTimeout: 5 * time.Second,  // 超过5秒连接不上超时
	})

	return cli, err
}

func RegETCDService(cli *clientv3.Client, serviceName string, host string, port int) error {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	// 存值
	_, err := cli.Put(ctx, serviceName, fmt.Sprintf("%s:%d", host, port))
	return err
}

func GetETCDValue(cli *clientv3.Client, serviceName string) (string, error) {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	v, err := cli.Get(ctx, serviceName)
	kvs := v.Kvs
	if len(kvs) == 0 {
		return "", errors.New("no value")
	}
	return string(kvs[0].Value), err
}

type MsETCDRegister struct {
	cli *clientv3.Client
}

func (m *MsETCDRegister) CreateCli(option Option) error {
	cli, err := clientv3.New(clientv3.Config{
		Endpoints:   option.Endpoints, // 节点
		DialTimeout: 5 * time.Second,  // 超过5秒连接不上超时
	})
	m.cli = cli

	return err
}

func (m *MsETCDRegister) RegisterService(serviceName string, host string, port int) error {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	// 存值
	_, err := m.cli.Put(ctx, serviceName, fmt.Sprintf("%s:%d", host, port))
	return err
}

func (m *MsETCDRegister) Close() error {
	return m.cli.Close()
}

func (m *MsETCDRegister) GetValue(serviceName string) (string, error) {

	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	v, err := m.cli.Get(ctx, serviceName)
	kvs := v.Kvs
	if len(kvs) == 0 {
		return "", errors.New("no value")
	}
	return string(kvs[0].Value), err
}
